<template>
  <ul class="xitongYonghu" style="z-index: 1">
    <li class="xitongYonghu-top">
      <ul class="xitong-search" style="padding: 10px;display: flex;justify-content: space-between;align-items: center;">
        <div class="operation-group">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>添加
          </el-button>
        </div>
      </ul>

      <!-- 修改添加领域对话框 -->
      <el-dialog v-model="dialogFormVisible" title="添加领域" width="30%">
        <el-form :model="form" label-width="80px">
          <el-form-item label="领域名称" required>
            <el-autocomplete
              v-model="form.areaName"
              :fetch-suggestions="querySearch"
              clearable
              class="inline-input w-full"
              placeholder="请选择或输入领域名称"
              @select="handleSelect"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addArea">确认添加</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 领域列表 -->
      <li>
        <el-table
          ref="tableRef"
          :data="itemsArr"
          style="width: 100%"
          border
          v-loading="isLoading"
        >
          <el-table-column prop="areaId" label="ID" width="100" />
          <el-table-column prop="areaName" label="领域名称" min-width="200" />
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button type="danger" size="small" @click="handleDelete(scope.row.areaId)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="pagination"
        />
      </li>
    </li>
  </ul>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { Plus, Delete } from '@element-plus/icons-vue'

// 修改领域选项相关数据
const areaOptions = ref([])

// 修改加载领域选项的方法
const loadAllAreas = async () => {
  try {
    const response = await axios.get('consultants/selectAreaList2')
    if (response.data.code === 200) {
      console.log('领域列表数据:', response.data.data)
      // 修改数据映射，使用完整的对象
      areaOptions.value = response.data.data.map(area => ({
        value: area.areaName,  // 显示的文本
        areaId: area.areaId    // 保存ID以备用
      }))
      console.log('处理后的选项:', areaOptions.value)
    }
  } catch (error) {
    console.error('获取领域列表失败:', error)
    ElMessage.error('获取领域选项失败')
  }
}

// 搜索建议方法
const querySearch = (queryString, cb) => {
  const results = queryString
    ? areaOptions.value.filter(createFilter(queryString))
    : areaOptions.value
  cb(results)
}

// 创建过滤器
const createFilter = (queryString) => {
  return (area) => {
    return area.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  }
}

// 修改选择建议项处理
const handleSelect = (item) => {
  form.value.areaName = item.value
  form.value.areaId = item.areaId  // 保存选中项的ID
}

// 表单数据
const form = ref({
  areaId: '',
  areaName: '',
  consultantId: ''
})

// 对话框控制
const dialogFormVisible = ref(false)
const isShow = ref(true)
const isLoading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const itemsArr = ref([])
const tableRef = ref(null)

// 组件卸载标志
const isComponentUnmounted = ref(false)

// 获取领域列表
const getAreaList = async () => {
  if (isComponentUnmounted.value) return
  
  try {
    let user = sessionStorage.getItem('user')
    if (!user) {
      ElMessage.error('请先登录')
      return
    }
    user = JSON.parse(user)

    isLoading.value = true
    const response = await axios.get('consultants/selectAreaById', {
      params: {
        consultantId: user.consultantId
      }
    })

    if (isComponentUnmounted.value) return

    console.log('响应数据:', response.data)
    if (response.data.code === 200 && !isComponentUnmounted.value) {
      itemsArr.value = response.data.data
      total.value = itemsArr.value.length
      isShow.value = true
    }
  } catch (error) {
    if (!isComponentUnmounted.value) {
      console.error('获取领域列表失败:', error)
      ElMessage.error('获取领域列表失败')
      itemsArr.value = []
      total.value = 0
    }
  } finally {
    if (!isComponentUnmounted.value) {
      isLoading.value = false
    }
  }
}

// 组件生命周期钩子
onUnmounted(() => {
  isComponentUnmounted.value = true
})

onMounted(async () => {
  isComponentUnmounted.value = false
  getAreaList()
})

// 修改添加领域方法
const addArea = async () => {
  try {
    // 再次检查数量（以防对话框打开后通过其他方式添加）
    if (itemsArr.value.length >= 3) {
      ElMessage.warning('最多只能添加三个擅长领域')
      dialogFormVisible.value = false
      return
    }

    if (!form.value.areaName) {
      ElMessage.error('领域名称不能为空')
      return
    }
    let user = sessionStorage.getItem('user')
    if (!user) {
      ElMessage.error('请先登录')
      return
    }
    user = JSON.parse(user)

    // 修改重复检查逻辑
    const isDuplicate = itemsArr.value.some(item => 
      item.areaName === form.value.areaName ||  // 检查名称
      item.areaId === form.value.areaId         // 检查ID
    )
    if (isDuplicate) {
      ElMessage.warning(`已添加过"${form.value.areaName}"领域`)
      return
    }

    // 构造请求数据
    const consultantSpecializationArea = {
      consultantId: user.consultantId,
      areaId: form.value.areaId,
      areaName: form.value.areaName
    }

    const response = await axios.post('consultants/insertArea', consultantSpecializationArea)
    
    if (response.data.code === 200) {
      ElMessage.success('添加成功')
      dialogFormVisible.value = false
      getAreaList()
      form.value = { areaId: '', areaName: '', consultantId: '' }
    } else {
      throw new Error(response.data.msg || '添加失败')
    }
  } catch (error) {
    console.error('添加失败:', error)
    ElMessage.error(error.message || '添加失败')
  }
}

// 处理删除
const handleDelete = async (areaId) => {
  try {
    let user = sessionStorage.getItem('user')
    if (!user) {
      ElMessage.error('请先登录')
      return
    }
    user = JSON.parse(user)

    await ElMessageBox.confirm('确定要删除该领域吗？', '提示', {
      type: 'warning'
    })
    
    const response = await axios.delete('consultants/deleteAreaById', {
      params: {
        consultantId: user.consultantId,
        areaId: areaId
      }
    })
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      getAreaList()
    } else {
      throw new Error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 分页处理
const handleSizeChange = async (size) => {
  pageSize.value = size
  currentPage.value = 1
  await getAreaList()
}

const handleCurrentChange = async (page) => {
  currentPage.value = page
  await getAreaList()
}

// 添加处理添加按钮点击的方法
const handleAdd = async () => {
  // 先检查当前领域数量
  if (itemsArr.value.length >= 3) {
    ElMessage.warning('最多只能添加三个擅长领域')
    return
  }
  
  await loadAllAreas() // 点击添加按钮时获取最新的领域选项
  dialogFormVisible.value = true
}
</script>

<style scoped>
/* 添加自动完成输入框的样式 */
.inline-input {
  width: 100%;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-pagination) {
  margin-top: 20px;
  justify-content: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.operation-group {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>